package com.example.androidtest;

import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

/**
 * SpanStyle工具类
 * 可实现简单的效果，当前工程暂未使用
 *
 * @author mxiaoyong
 */
public class SpanStyleUtils {

    private int beforeColor;
    private int afterColor;
    private SpannableStringBuilder ssb;
    private TextView textView;
    private SpannableSbBeforeClick sbBeforeClick = new SpannableSbBeforeClick();
    private SpannableSbAfterClick afterClick = new SpannableSbAfterClick();

    public SpanStyleUtils(SpannableStringBuilder ssb, TextView textView,
                          int beforeColor, int afterColor) {
        this.ssb = ssb;
        this.textView = textView;
        this.beforeColor = beforeColor;
        this.afterColor = afterColor;
    }

    public ClickableSpan getSpanStyle() {
        return this.sbBeforeClick;
    }

    /**
     * 点击前效果
     */
    private class SpannableSbBeforeClick extends ClickableSpan {

        @Override
        public void onClick(@NonNull View widget) {
            // 第四个参数flags,整了半天才明白是干啥的
            // 一般用于EditText,在特殊文本的前后追加文本时是否与特殊文本效果相同
            // 或配合insert使用
            if (!TextUtils.isEmpty(textView.getText().toString())) {
                SpanStyleUtils.this.ssb.setSpan(SpanStyleUtils.this.afterClick, 0, 1,
                        SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
                SpanStyleUtils.this.textView.setText(SpanStyleUtils.this.ssb);
            }
        }

        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            // 设置文字颜色
            ds.setColor(SpanStyleUtils.this.beforeColor);
            // 去掉默认的下划线效果
            ds.setUnderlineText(false);
        }
    }


    /**
     * 点击后效果
     */
    private class SpannableSbAfterClick extends ClickableSpan {

        @Override
        public void onClick(@NonNull View widget) {
        }

        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            super.updateDrawState(ds);
            ds.setColor(SpanStyleUtils.this.afterColor);
            // 去掉下划线
            ds.setUnderlineText(false);
        }
    }
}